const fs = require("fs");
const path = require("path");
const PDFDocument = require("pdfkit");
const numberToChinese = require("./utils/chineseNumbers"); // 数字转中文大写
const ennumberToChinese = require("./utils/englishNumbers"); // 数字转英文
const util = require('util');
const mkdir = util.promisify(fs.mkdir);
// let file_to_path="E:\\A_working_directory\\hugo_project\\邓云格-项目\\资源\\Mass-production-files测试\\content"

// 文件类型定义
// const fileTypes = {
//   zh: [
//     // 中文的类型和文件列表
//     [
//       {
//         type: "course",
//         sourceFiles: [
//           "../dav陪标/Excel课程/标2/Excel_cn.md",
//           "../dav陪标/MySQL课程/标2/sql课程目录/cn/MySQL课程内容_cn.md",
//           "../dav陪标/python课程/标2/Python课程.md",
//           "../dav陪标/tableau课程/标2/Tableau_cn.md",
//         ],
//       },
//       {
//         type: "experiment",
//         sourceFiles: [
//           "../dav陪标/Excel课程/标2/Excel_cn.md",
//           "../dav陪标/MySQL课程/标2/sql课程目录/cn/MySQL高级查询与优化实验手册.md",
//           "../dav陪标/python课程/标2/Python课程.md",
//           "../dav陪标/tableau课程/标2/Tableau_cn.md",
//         ],
//       },
//       {
//         type: "case",
//         sourceFiles: [
//           "../dav陪标/综合案例/标0/Excel/Excel(CN).md",
//           "../dav陪标/综合案例/标0/MySQL/MySQL综合案例（cn）.md",
//           "../dav陪标/综合案例/标0/python/python （cn）.md",
//           "../dav陪标/综合案例/标0/tableau/tableau（cn）.md",
//         ],
//       },
//       {
//         type: "video",
//         sourceFiles: [
//           "../dav陪标/Excel课程/标2/Excel_cn.md",
//           "../dav陪标/MySQL课程/标2/sql课程目录/cn/MySQL课程内容_cn.md",
//           "../dav陪标/python课程/标2/Python课程.md",
//           "../dav陪标/tableau课程/标2/Tableau_cn.md",
//         ],
//       },
//     ],
//   ],
//   en: [
//     // 英文的类型和文件列表
//     [
//       {
//         type: "course",
//         sourceFiles: [
//           "../dav陪标/Excel课程/标2/Excel_en.md",
//           "../dav陪标/MySQL课程/标2/sql课程目录/en/MySQL Course  _en.md",
//           "../dav陪标/python课程/标2/Python Course.md",
//           "../dav陪标/tableau课程/标2/Tableau_en.md",
//         ],
//       },
//       {
//         type: "experiment",
//         sourceFiles: [
//           "../dav陪标/Excel课程/标2/Excel_en.md",
//           "../dav陪标/MySQL课程/标2/sql课程目录/en/MySQL Advanced Queries and Optimization.md",
//           "../dav陪标/python课程/标2/Python Course.md",
//           "../dav陪标/tableau课程/标2/Tableau_en.md",
//         ],
//       },
//       {
//         type: "case",
//         sourceFiles: [
//           "../dav陪标/综合案例/标0/Excel/Excel(EN).md",
//           "../dav陪标/综合案例/标0/MySQL/MySQL综合案例（en）.md",
//           "../dav陪标/综合案例/标0/python/python数据分析（EN）.md",
//           "../dav陪标/综合案例/标0/tableau/tableau（en）.md",
//         ],
//       },
//       {
//         type: "video",
//         sourceFiles: [
//           "../dav陪标/Excel课程/标2/Excel_en.md",
//           "../dav陪标/MySQL课程/标2/sql课程目录/en/MySQL Course  _en.md",
//           "../dav陪标/python课程/标2/Python Course.md",
//           "../dav陪标/tableau课程/标2/Tableau_en.md",
//         ],
//       },
//     ],
//   ],
// };

let chapterCount = 0;

// 创建一个异步函数来处理章节
async function processChapter(typeFolder,sourceFile, targetRootFolder, language) {
  return new Promise((resolve, reject) => {
    fs.readFile(sourceFile, "utf-8", (err, data) => {
      if (err) {
        return reject(err);
      }

      let subchapterCount = 0;
      const regex = /^(#+)\s(.*)/gm;
      let match;
      let titlelist = [];

      while ((match = regex.exec(data)) !== null) {
        const level = match[1].length;
        let title = match[2].trim();
        title = title.replace(/\*/g, "").replace(/：/g, " ");

        if (level === 2) {
          titlelist.push(title);
    console.log("weight",chapterCount);
          chapterCount++;

          subchapterCount = 0;

          const chapterFolder = `${chapterCount.toString().padStart(2, "0")}`;
          const chapterPath = path.join(targetRootFolder, chapterFolder);
          const weight = `${chapterCount.toString()}`;

          fs.mkdir(chapterPath, { recursive: true }, (err) => {
            if (err) {
              return reject(err);
            } else {
            //   console.log(`已创建章节文件夹: ${chapterPath}`);
              const indexPath = path.join(chapterPath, "_index.md");

              if (!fs.existsSync(indexPath)) {
                // 判断语言类型，执行不同的逻辑
                let titlenum=""
                let date=""
                let entitle=""
                let engtitle=""
                if(typeFolder==="course"){
                  date="2023-10-30T16:24:40+08:00"
                }
                if(typeFolder==="experiment"){
                  date="2023-08-28T16:24:40+08:00"
                }
                if(typeFolder==="case"){
                  date="2023-05-20T16:24:40+08:00"
                }
                if(typeFolder==="video"){
                  date="2023-09-25T16:24:40+08:00"
                }
                if( language === "en"){
                  title = title.replace(/^\d+\./, "");
                  title = title.replace(/^\d+、/, "");
                  title = title.replace(/.*、/, "  ");
                  title = title.replace(/.*:\s+/, "");
                  titlenum =   `Chapter ${ennumberToChinese(weight)}`;
                  entitle = title;
              }
                if( language === "zh"){
                    title = title.replace(/^\d+、/, "  ");
                    title = title.replace(/\*/g, "").replace(/：/g, " ");
                    title = title.replace(/.*部分/, "");
                    title = title.replace(/.*、/, "  ");
                    title = title.replace(/.*章/, "");
                    titlenum =`第${numberToChinese(weight)}章`
                    // 当检测到英文标题时，存储英文标题到外部作用域变量
                    // engtitle = entitle;
                }
                const indexContent =`
---
title: "${titlenum} ${title}"
date: "${date}"
type: 'first'
draft: true
weight: '${weight}'
entitle: "${entitle}"
description: ""
resources:
- src1: ""
---`;

                fs.writeFile(indexPath, indexContent, (err) => {
                  if (err) {
                    return reject(err);
                  } else {
                    // console.log(`已创建章节的 _index.md文件: ${indexPath}`);
                  }
                });
              }
            }
            resolve(); // 章节处理完成
          });
        } else if (level === 3 || level === 4) {
          subchapterCount++;

          const chapterFolder = `${chapterCount.toString().padStart(2, "0")}`;
          const subchapterFolder = `${chapterCount}.${subchapterCount
            .toString()
            .padStart(1, "0")}`;
          const chapterPath = path.join(
            targetRootFolder,
            chapterFolder,
            subchapterFolder
          );
          const weight = `${subchapterCount.toString()}`;

          fs.mkdir(chapterPath, { recursive: true }, (err) => {
            if (err) {
              return reject(err);
            } else {
            //   console.log(`已创建文件夹: ${chapterPath}`);

              // 判断语言类型，执行不同的逻辑
              const titlenum =
                language === "zh"
                  ? `第${numberToChinese(weight)}节`
                  : `Section ${ennumberToChinese(weight)}`;
let   videoName = title.replace(/[<>]/g, "_");
let  pdf = title.replace(/[<>]/g, "_");
              let subchapterIndexContent;

              if (targetRootFolder.includes("video")) {
                // 判断语言类型，执行不同的逻辑
                if (language === "zh") {
                  title = title.replace(/^第\d+节\s+/, "");
                  let pdfName = title.replace(/\//g, "_");

                  pdfName = title.replace(/^\d+\.\d+\s*/, "");
                  title = title.replace(/^\d+\.\d+\s*/, "");
                  title = title.replace(/.*节\s+/, "");
                  title = title.replace(/^\d+、/, "");
                  // title = title.replace(/\d+/g, "").trim();
                  pdfName = title.replace(/[<>]/g, "_");
                  const regex = `/^\d+、`;
                  subchapterIndexContent =`---
title: "${titlenum} ${title.replace(regex, "")}"
entitle: ""
date: 2021-01-30T16:24:40+08:00
draft: true
image: "image/course/analysis_01.png"
description: ""
series: 1 
weight: '${weight}'
resources:
- src: ""
  title: 
  image: '/themes/wiseinsight/static/element/pdf.png'
  params:    
---
{{< video title="${titlenum} ${title.replace(regex,"")}" src="videos/${pdfName}.mp4" >}}`;
                }
                if (language === "en") {
                  let pdfName = title.replace(/\//g, "_");
                  pdfName = title.replace(/[<>]/g, "_");
                  pdfName = pdfName.replace(/^.+:/, "");
                  pdfName = pdfName.replace(/\?/g, "");
                  pdfName = pdfName.replace(/^\d+、/, "");
                 
                  title = title.replace(/\*/g, "").replace(/：/g, " ");
                  title = title.replace(/^.+:/, "");
                  title = title.replace(/^.+,/, "");
                  title = title.replace(/.*\d+\.\d+/, "");
                  title = title.replace(/^\d+、/, "");
                  // 根据需要自定义小节标题的格式
                  const titlenum = `Section ${ennumberToChinese(weight)}`;
                  subchapterIndexContent = `---
title: "${titlenum} ${title.replace(regex, "")}"
entitle: ""
date: 2021-01-30T16:24:40+08:00
draft: true
image: "image/course/analysis_01.png"
description: ""
series: 1 
weight: '${weight}'
resources:
- src: ""
  title: 
  image: '/themes/wiseinsight/static/element/pdf.png'
  params:
    
---
{{< video title="${titlenum} ${title.replace(
                    regex,
                    ""
                  )}" src="videos/${pdfName}.mp4" >}}
`;
                }

                // 其余视频处理逻辑
                const videosFolder = path.join(chapterPath, "videos");
                fs.mkdir(videosFolder, { recursive: true }, (err) => {
                  if (err) {
                    console.error(
                      `创建 "videos" 文件夹时发生错误: ${videosFolder}`
                    );
                    return reject(err);
                  } else {
                    // console.log(`已创建 "videos" 文件夹: ${videosFolder}`);
                    // 创建一个空的Buffer，用于表示空的视频内容
                    const emptyBuffer = Buffer.from([]);

                    // 指定目标视频文件的完整路径
                    const videoFilePath = path.join(
                      videosFolder,
                      `${videoName}.mp4`
                    );

                    // 写入Buffer到视频文件
                    fs.writeFile(videoFilePath, emptyBuffer, (err) => {
                      if (err) {
                        console.error("创建视频文件时出错:", err);
                      } else {
                        // console.log(
                        //   `emptyVideo.mp4 创建成功于 ${videoFilePath}.`
                        // );
                        resolve(); // 小节处理完成
                      }
                    });
                  }
                });
                // ...
              } else {
                // 判断语言类型，执行不同的逻辑
                if (language === "zh") {
                  let pdfName = title.replace(/\//g, "_");

                  pdfName = title.replace(/^\d+\.\d+\s*/, "");
                  title = title.replace(/^\d+\.\d+\s*/, "");
                  title = title.replace(/.*节\s+/, "");
                  title = title.replace(/^\d+、/, "");
                  //正则匹配数字替换为空格
                  // title = title.replace(/\d+/g, "").trim();
                  pdfName = title.replace(/[<>]/g, "_");

                  subchapterIndexContent = `---
title: "${titlenum} ${title.replace(regex, "")}"
entitle: ""
date: 2021-01-30T16:24:40+08:00
draft: true
image: "image/course/analysis_01.png"
description: ""
series: 1
weight: '${weight}'
resources:
- src: ""
  title:
  image: '/themes/wiseinsight/static/element/pdf.png'
  params:
    
---
{{< pdf src="pdf/${pdfName}.pdf" >}}
`;
                }
                if (language === "en") {
                  let pdfName = title.replace(/\//g, "_");
                  pdfName = title.replace(/[<>]/g, "_");
                  pdfName = pdfName.replace(/^.+:/, "");
                  pdfName = pdfName.replace(/\?/g, "");
                  pdfName = pdfName.replace(/^\d+、/, "");
                  pdfName = pdfName.replace(/^\d+\.\d+\s*/, '');
                  title = title.replace(/\*/g, "").replace(/：/g, " ");
                  title = title.replace(/^.+:/, "");
                  title = title.replace(/^.+,/, "");
                  title = title.replace(/.*\d+\.\d+/, "");
                  title = title.replace(/^\d+、/, "");
                  subchapterIndexContent = `---
title: "${titlenum} ${title.replace(regex, "")}"
entitle: ""
date: 2021-01-30T16:24:40+08:00
draft: true
image: "image/course/analysis_01.png"
description: ""
series: 1
weight: '${weight}'
resources:
- src: ""
  title:
  image: '/themes/wiseinsight/static/element/pdf.png'
  params:
    
---
{{< pdf src="pdf/${pdfName}.pdf" >}}
`;
                }

                // 其余PDF处理逻辑
                // 在处理章节的逻辑中添加生成PDF的部分
                const pdfFolder = path.join(chapterPath, "pdf");

                fs.mkdir(pdfFolder, { recursive: true }, (err) => {
                  if (err) {
                    return reject(err);
                  } else {
                    // console.log(`已创建 PDF 文件夹: ${pdfFolder}`);

                    pdfName = title.replace(/[<>]/g, "_");
                    pdfName = pdfName.replace(/\?/g, "");
                    const pdfPath = path.join(pdfFolder, `${pdf}.pdf`);
                    const doc = new PDFDocument();
                    const stream = doc.pipe(fs.createWriteStream(pdfPath));
                    pdfName = title.replace(/[<>]/g, "_");
                    // 在 PDF 文件中添加内容，可以根据需要自定义
                    doc.fontSize(16);
                    doc.text(`这是 ${pdfName} 的 PDF 文件`);

                    // 结束 PDF 创建
                    doc.end();
                    console.log(`已创建 PDF 文件: ${pdfPath}`);
                    resolve(); // PDF创建完成
                  }
                });
              }

              const subchapterIndexPath = path.join(chapterPath, "index.md");
              fs.writeFile(
                subchapterIndexPath,
                subchapterIndexContent,
                (err) => {
                  if (err) {
                    return reject(err);
                  } else {
                    console.log(
                      `已创建小节的 _index.md 文件: ${subchapterIndexPath}`
                    );
                    resolve(); // 小节处理完成
                  }
                }
              );
            }
          });
        }
      }
    });
  });
}


// 使用Promise.all确保按顺序执行处理章节的操作
async function processAllChapters(file_to_path, fileTypes) {
  async function processLanguageSection(languageFolder, typeList) {
    for (const typeFiles of typeList) {
      for (const file of typeFiles) {
        const typeFolder = file.type;
        console.log(typeFolder);
        const targetRootFolder = path.join(file_to_path, languageFolder, typeFolder);

        try {
          await mkdir(targetRootFolder, { recursive: true });
          chapterCount = 0;
          console.log(`已创建文件夹: ${targetRootFolder}`);

          for (const sourceFile of file.sourceFiles) {
            console.log(`Processing files for type: ${typeFolder} (${languageFolder})`);
            await processChapter(typeFolder,sourceFile, targetRootFolder, languageFolder);
          }
          
          chapterCount = 1;
          console.log("chapterCount has been reset to 0.");
        } catch (err) {
          console.error(`创建文件夹时发生错误: ${targetRootFolder}`);
          console.error(err);
        }
      }
    }
  }

  await processLanguageSection("zh", fileTypes.zh);
  await processLanguageSection("en", fileTypes.en);
}

  // 调用处理所有章节的函数
  // (async () => {
  //   await processAllChapters();
  //   console.log("All chapters processed.");
  //   // 所有章节处理完成后执行重置操作
  //   chapterCount = 0;
  //   console.log("chapterCount has been reset to 0.");
  // })();

  module.exports = {
    processAllChapters,
  };